package com.xaicode.learn.netty.dubborpc.netty;

import com.xaicode.learn.netty.dubborpc.provider.HelloServiceImpl;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 21:37
 */
@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    private final String TEST_METHOD_PREFIX = "HelloService#hello#";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // read client msg
        log.info("receive client msg: {}", msg);

        // check msg protocol
        // eg: client msg is like this "ClassName#MethodName#Params" -> "HelloService#hello#haha"
        if (msg.toString().startsWith(TEST_METHOD_PREFIX)) {
            String result = new HelloServiceImpl()
                    .hello(msg.toString().replace(TEST_METHOD_PREFIX, ""));
            ctx.writeAndFlush(result);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
